package com.qyc.aspect;

import com.alibaba.fastjson.JSON;
import com.qyc.annotation.SystemLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @className: LogAspect
 * @Description: AOP切面类
 * @author: qinyc
 * @date: 2023/6/21 15:31
 * @version: v1.0
 */

@Aspect //切面类
@Component
@Slf4j
public class LogAspect {
    /**
     * @Author qinyc
     * @Description  配置切入点
     * @version: v1.0
     * @Date 15:55 2023/6/21
     *     execution :匹配某个切入点 在service包下的所有方法都是切入点
     *     * com.qyc.service..*.*(..) 切入点规则
     **/
    @Pointcut("@annotation(com.qyc.annotation.SystemLog)")
    public void logPointCut(){
    }


    /**
     * @Author qinyc
     * @Description  环绕通知
     * @version: v1.0
     * @Date 16:07 2023/6/21
     **/
    @Around("logPointCut()")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        try {
            //核心方法执行之前执行的代码
            handleBefore(joinPoint);
            //连接点执行核心方法
            result = joinPoint.proceed();
            //核心方法执行完执行的代码
            handleAfter(result);
        } finally {
            // 结束后换行（根据不同系统匹配不同的换行符）
            log.info("=======End=======" + System.lineSeparator());
        }
        //正常返回结果
        return result;
    }

    /**
     * @Author qinyc
     * @Description  执行核心方法之前执行的方法
     * @version: v1.0
     * @Date 16:15 2023/6/21
     **/
    private void handleBefore(ProceedingJoinPoint joinPoint) {
        //获取HttpServletRequest对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取核心方法方法上的注解对象
        SystemLog systemLog = getSystemLog(joinPoint);
        log.info("=======开始======");
        // 打印请求 URL
        log.info("URL（请求地址）: {}",request.getRequestURL());
        // 打印描述信息
        log.info("BusinessName（接口信息描述）: {}",systemLog.businessName());
        // 打印 Http method
        log.info("HTTP Method（请求方式）: {}",request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method（类信息和方法名组成的全限路径）: {}.{}",joinPoint.getSignature().getDeclaringTypeName(),((MethodSignature) joinPoint.getSignature()).getName());
        // 打印请求的 IP
        log.info("IP（访问IP地址）: {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args（请求参数）: {}", JSON.toJSONString(joinPoint.getArgs()) );
    }

    /**
     * @Author qinyc
     * @Description  执行核心方法之后执行的代码
     * @version: v1.0
     * @Date 16:18 2023/6/21
     **/
    private void handleAfter(Object ret) {
        // 打印出参
        log.info("Response（响应数据）: {}", JSON.toJSONString(ret));
    }
    
    
    /**
     * @Author qinyc
     * @Description  获取核心方法方法上的注解对象
     * @version: v1.0
     * @Date 16:19 2023/6/21
     **/
    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        SystemLog systemLog = methodSignature.getMethod().getAnnotation(SystemLog.class);
        return systemLog;
    }

}
